#!/bin/bash

# Codelin运行脚本 - 解决库路径问题
# 
# 功能：
# 1. 自动设置仓颉运行时库路径
# 2. 支持CLI和TUI两种模式
# 3. 提供便捷的启动方式

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CODELIN_BINARY="$PROJECT_ROOT/target/release/bin/codelin"

# 仓颉运行时库路径
CANGJIE_SDK_PATH="/Users/louloulin/Documents/linchong/cj/CangjieSDK-Darwin"
CANGJIE_RUNTIME_PATH="$CANGJIE_SDK_PATH/cangjie/runtime/lib/darwin_aarch64_llvm"
STDX_PATH="$PROJECT_ROOT/libs/cangjie-stdx-mac-aarch64-1.0.0.1/darwin_aarch64_llvm/dynamic/stdx"
MAGIC_PATH="$PROJECT_ROOT/target/release/magic"

# 检查文件是否存在
check_file_exists() {
    local file_path="$1"
    local description="$2"
    
    if [ ! -f "$file_path" ]; then
        echo -e "${RED}❌ $description 不存在: $file_path${NC}"
        return 1
    fi
    return 0
}

# 检查目录是否存在
check_dir_exists() {
    local dir_path="$1"
    local description="$2"
    
    if [ ! -d "$dir_path" ]; then
        echo -e "${RED}❌ $description 不存在: $dir_path${NC}"
        return 1
    fi
    return 0
}

# 验证环境
validate_environment() {
    echo -e "${BLUE}🔍 验证Codelin运行环境...${NC}"
    
    # 检查Codelin可执行文件
    if ! check_file_exists "$CODELIN_BINARY" "Codelin可执行文件"; then
        echo -e "${YELLOW}💡 请先构建项目: cd $PROJECT_ROOT && cjpm build${NC}"
        exit 1
    fi
    
    # 检查仓颉运行时库
    if ! check_file_exists "$CANGJIE_RUNTIME_PATH/libcangjie-runtime.dylib" "仓颉运行时库"; then
        echo -e "${YELLOW}💡 请确保仓颉SDK已正确安装在: $CANGJIE_SDK_PATH${NC}"
        exit 1
    fi
    
    # 检查stdx库
    if ! check_dir_exists "$STDX_PATH" "stdx库目录"; then
        echo -e "${YELLOW}💡 请确保stdx库存在: $STDX_PATH${NC}"
        exit 1
    fi
    
    # 检查magic库
    if ! check_dir_exists "$MAGIC_PATH" "magic库目录"; then
        echo -e "${YELLOW}💡 请先构建项目以生成magic库${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ 环境验证通过${NC}"
}

# 设置库路径
setup_library_path() {
    export DYLD_LIBRARY_PATH="$CANGJIE_RUNTIME_PATH:$STDX_PATH:$MAGIC_PATH"
    
    if [ "$VERBOSE" = "true" ]; then
        echo -e "${BLUE}📚 库路径设置:${NC}"
        echo "  仓颉运行时: $CANGJIE_RUNTIME_PATH"
        echo "  stdx库: $STDX_PATH"
        echo "  magic库: $MAGIC_PATH"
        echo ""
    fi
}

# 显示使用帮助
show_help() {
    echo -e "${BLUE}🚀 Codelin运行脚本${NC}"
    echo ""
    echo "用法:"
    echo "  $0 [选项] [参数...]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示此帮助信息"
    echo "  -v, --verbose  显示详细信息"
    echo "  --tui          强制启动TUI模式"
    echo "  --cli          强制启动CLI模式"
    echo ""
    echo "示例:"
    echo "  $0                                    # 启动TUI交互模式"
    echo "  $0 \"生成一个Python计算器\"            # CLI直接模式"
    echo "  $0 --help                            # 显示帮助"
    echo "  $0 --version                         # 显示版本"
    echo "  $0 -v \"创建Web API\"                  # 详细模式"
    echo ""
    echo "管道操作:"
    echo "  echo \"修复这个bug\" | $0              # 管道输入"
    echo ""
    echo "文件操作:"
    echo "  $0 --file main.py \"优化代码\"         # 文件模式"
    echo ""
}

# 解析命令行参数
parse_arguments() {
    VERBOSE=false
    FORCE_TUI=false
    FORCE_CLI=false
    CODELIN_ARGS=()
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -v|--verbose)
                VERBOSE=true
                shift
                ;;
            --tui)
                FORCE_TUI=true
                shift
                ;;
            --cli)
                FORCE_CLI=true
                shift
                ;;
            *)
                CODELIN_ARGS+=("$1")
                shift
                ;;
        esac
    done
}

# 运行Codelin
run_codelin() {
    if [ "$VERBOSE" = "true" ]; then
        echo -e "${BLUE}🚀 启动Codelin...${NC}"
        echo "  可执行文件: $CODELIN_BINARY"
        echo "  参数: ${CODELIN_ARGS[*]}"
        echo ""
    fi
    
    # 切换到项目目录
    cd "$PROJECT_ROOT"
    
    # 执行Codelin
    if [ ${#CODELIN_ARGS[@]} -eq 0 ] && [ "$FORCE_CLI" != "true" ]; then
        # 无参数时启动TUI模式
        if [ "$VERBOSE" = "true" ]; then
            echo -e "${GREEN}🎨 启动TUI交互模式${NC}"
        fi
        exec "$CODELIN_BINARY"
    else
        # 有参数时启动CLI模式
        if [ "$VERBOSE" = "true" ]; then
            echo -e "${GREEN}💻 启动CLI模式${NC}"
        fi
        exec "$CODELIN_BINARY" "${CODELIN_ARGS[@]}"
    fi
}

# 主函数
main() {
    # 解析参数
    parse_arguments "$@"
    
    # 验证环境
    validate_environment
    
    # 设置库路径
    setup_library_path
    
    # 运行Codelin
    run_codelin
}

# 错误处理
trap 'echo -e "${RED}❌ 脚本执行失败${NC}"; exit 1' ERR

# 执行主函数
main "$@"
